package com.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blog.entity.ArticleComment;
import com.blog.entity.SysDictionary;
import com.blog.entity.SysMessage;
import com.blog.entity.SysUser;
import com.blog.redis.RedisUtil;
import com.blog.service.*;

import com.blog.util.dto.AjaxResult;
import com.blog.util.laydto.LayDto;
import com.blog.util.laydto.LayDtoUtil;
import com.blog.util.sensitive.SensitiveWordUtil;
import com.blog.util.uuid.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author gxcc
 * @create 2021/11/13 18:16
 */
@Controller
@RequestMapping("comment")
@Slf4j
public class ArticleCommentController {


    @Resource
    ArticleCommentService commentService;

    @Resource
    SysUserService userService;

    @Resource
    RedisUtil redisUtil;

    @Resource
    SysDictionaryService dictionaryService;

    @Resource
    SysMessageService messageService;

    @Resource
    SysSensitiveService sensitiveService;

    /**
     * 获取当前博客的评论
     * @param
     * @return
     */
    @PostMapping("article/getComment")
    @ResponseBody
    public AjaxResult queryComment(@RequestParam("articleId") String articleId){
        List<Map<String,Object>> list = commentService.queryCommentById(articleId);
        return AjaxResult.success(list);
    }

    @PostMapping("articleDetail/saveComment")
    @ResponseBody
    public AjaxResult saveComment(@RequestParam("articleId") String articleId, @RequestParam("comment") String comment){
        Subject subject = SecurityUtils.getSubject();
        SysUser sysUser = (SysUser)subject.getPrincipal();
        if (sysUser == null){
            return AjaxResult.error("请先登录");
        }
        Set<String> strings = sensitiveService.listSensitiveWords();
        boolean isOk = sensitiveService.filterSensitive(comment);
        if (isOk){
            //获取语句中的敏感词
            Set<String> set = SensitiveWordUtil.getSensitiveWord(strings,comment);
            String str = String.join(", ", set);
            return AjaxResult.error("含有违规字符,为: "+str);
        }
        ArticleComment articleComment = new ArticleComment(UUIDUtils.getUUId(),articleId,comment,sysUser.getId(),1, new Date(),new Date());
        commentService.save(articleComment);
        return AjaxResult.success();
    }

    @GetMapping("username/changeUserActive")
    @ResponseBody
    public AjaxResult preventXss(){
        Subject subject = SecurityUtils.getSubject();
        SysUser sysUser = (SysUser) subject.getPrincipal();

        Object data = redisUtil.get(sysUser.getId() + "xss");
        if (data == null){
            redisUtil.set(sysUser.getId()+"xss","1");
        }else {
            redisUtil.incr(sysUser.getId()+"xss",1);
        }
        Object object = redisUtil.get(sysUser.getId() + "xss");

        Integer count = Integer.valueOf(object.toString());
        if (count >= 3){
            //强制退出登录
            subject.logout();
            //更改用户状态为-1
            sysUser.setActive(-1);
            userService.lockUserById(sysUser.getId());
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 后台表格数据接口
     * @param
     * @return
     */
    @GetMapping("/admin/tableList")
    @ResponseBody
    public LayDto tableList(@RequestParam(value = "comment",required = false) String comment,@RequestParam(value = "username",required = false) String username){
        List<Map<String, Object>> list = commentService.tableList(comment,username);
        return LayDtoUtil.returnSuccess(0,"", list.size(), list);
    }

    /**
     * 删除评论并通知到个人
     * @param
     * @return
     */
    @GetMapping("/admin/delete")
    public String deleteFrame(@RequestParam("commentId") String commentId, Model model){
        model.addAttribute("commentId",commentId);
        return "admin/article/comment/comment-delete";
    }

    /**
     * 后台获取删除原因下拉框
     * @param
     * @return
     */
    @GetMapping("/admin/deleteReason")
    @ResponseBody
    public AjaxResult getDeleteReasonData(){
        List<Map<String,String>> list = dictionaryService.getXmSelectDataBySign("delete_reason");
        return AjaxResult.success(list);
    }


    @PostMapping("/admin/deleteById")
    @ResponseBody
    public AjaxResult deleteCommentById(@RequestParam("commentId") String commentId,@RequestParam("delvalue") String delvalue,@RequestParam("deleteRemark") String deleteRemark){
        ArticleComment byId = commentService.getById(commentId);
        boolean update = commentService.removeById(byId.getId());
        if (update){
            SysUser user = userService.getById(byId.getCommentPerson());
            SysDictionary dictionary = dictionaryService.getById(delvalue);
            String value = dictionary.getValue();
            String content = "您的评论【"+byId.getComments()+"】因为【"+value+"】被删除，给您带来不便，请谅解";

            SysMessage sysMessage = new SysMessage(UUIDUtils.getUUId(),byId.getCommentPerson(),user.getNickname(),content,deleteRemark, byId.getId(),0,1,new Date(),new Date());
            messageService.save(sysMessage);
        }else {
            log.error("创建消息失败");
        }
        return AjaxResult.success();
    }


    @GetMapping("/user/queryNewMessage")
    @ResponseBody
    public AjaxResult getNewMessage(){
        Subject subject = SecurityUtils.getSubject();
        //获取当前登陆人
        SysUser sysUser = (SysUser)subject.getPrincipal();
        Map<String,Object> map = new HashMap<>();
        map.put("userId",sysUser.getId());
        List<Map<String,Object>> list = messageService.queryUserNewMessage(map);
        return AjaxResult.success(list);
    }

//    @GetMapping("/admin/queryCommentByCondition")
//    @ResponseBody
//    public LayDto queryCommentByCondition(){
//        List<Map<String,Object>> list = commentService.queryCommentByCondition(comment,username);
//        return LayDtoUtil.returnSuccess(0,"",list.size(),list);
//    }
}
